package com.gxitsky.plugin.config;

import com.gxitsky.plugin.IFunction;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author gxing
 * @desc TODO
 * @date 2021/12/31
 */
@Configuration
//@EnableScheduling
public class CronJob {

    @Value("${function.jar.url}")
    private String jarUrl;

    // 更新函数的定时任务
//    @Scheduled(fixedDelay = 2000)
    public void updateFunction() {
        try {
            System.out.println("-----------job---------------");
//            URL url = new URL("jar:" + jarUrl + "!/");
            URL url = new URL("jar:file:///D:/service-impl-1.0.0-SNAPSHOT.jar!/");
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            JarFile jarFile = jarURLConnection.getJarFile();
            Enumeration<JarEntry> entries = jarFile.entries();

            URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                String entryName = jarEntry.getName();
                String className = entryName.replace("/", ".");
                if (jarEntry.isDirectory() || !className.startsWith("com.gxitsky.plugin") || !className.endsWith(".class")) {
                    continue;
                }
                String classPath = className.substring(0, entryName.length() - 6);
                Class<?> clazz = urlClassLoader.loadClass(classPath);
                boolean anInterface = clazz.isInterface();
                boolean assignableFrom3 = IFunction.class.isAssignableFrom(clazz);
                System.out.println(assignableFrom3);

            }



//            UpdateFunctionUtil.updateIfModified(jarUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新函数的内部工具类
//    private static class UpdateFunctionUtil extends FunctionUtil {
//        private static long lastModified = 0L;

//        private static synchronized void updateIfModified(String jarUrl) throws Exception {
//            URL url = new URL("jar:" + jarUrl + "!/");
//            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
//            long modified = jarURLConnection.getLastModified();
//            // 判断jar是否发生变化
//            if (lastModified == modified) {
//                return;
//            } else {
//                // 保存最新的修改时间
//                lastModified = modified;
//            }
//            Map<String, IFunction> functions = loadFunctions(url);
//            setFunctions(functions);
//        }
//    }
}
